#!/bin/bash
set -e
if [[ $# -ne 3 ]]; then
    echo "The format is as follows:"
    echo "./tinker-8.10.2.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
	echo ":param srcDir: 商业软件包存放目录绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then echo "请输入正确的构建路径"; exit 1; fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then echo "请输入正确的安装路径"; exit 1; fi
[[ "$1" = "$2" ]] && echo "构建路径与安装路径不能相同" && exit 1
buildpath=$1
installpath=$2
srcDir=$3
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi

cd $srcDir
tar -zxvf tinker-8.10.2.tar.gz && cd tinker
cp ./make/Makefile-apbs ./source/Makefile
cd source
sed -i -e "s|TINKERDIR =.*|TINKERDIR = $srcDir/tinker|" \
-e "s|APBS_LIBDIR =.*|APBS_LIBDIR = -L$apbslib|" Makefile
sed -i '151s/stdcall/pcs=aapcs/' $srcDir/tinker/fftw/api/f77api.c
sed -i '65s/stdcall/pcs=aapcs/' $srcDir/tinker/fftw/threads/f77api.c
make clean && make -j$(nproc) F77=flang OPTFLAGS="-Ofast -march=armv8.2-a -fsigned-char -ffp-contract=off -mtune=tsv110 -cpp -fopenmp"
mkdir -p $srcDir/tinker/bin/ && make install
mkdir -p $installpath/tinker-8.10.2/ && mv $srcDir/tinker/bin/  $installpath/tinker-8.10.2/bin/
cat>"$installpath/tinker-8.10.2/tinker_modulefiles"<<EOF
#%Module1.0
conflict tinker
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set tinker \$pwd
setenv tinker \$tinker
prepend-path PATH \$tinker/bin
EOF
